<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Org extends Model
{
  protected  $table='org';

  protected $fillable = [
      'user_id',
      'name',
      'type',
      'logo',
      'contact_name',
      'contact_phone',
      'contact_email',
      'contact_addr',
      'contact_province_id',
      'contact_province_name',
      'contact_city_id',
      'contact_city_name',
      'contact_county_id',
      'contact_county_name',

      'corporate_name',
      'corporate_id',
      'corporate_phone',
      'quality',
      'business_licence',
      'module_settings',
      'in_blacklist',
      'wechat_app_id',
      'wechat_app_secret',
      'wechat_verify_file',

      'cert_title',
      'cert_org',
      'cert_cachet',
      'cert_auth_org',

      'org_info',
      'org_manual',
      'org_service',
      'org_service_tel',

      'duiba_key',
      'duiba_secret',
      'score_settings',
      'score_name',

      'address',
      'real_name_register',
      'org_service_guide',
      'custom_config',
      'wechat_payment_merchant_id',
      'wechat_payment_key',
      'open_stars',
      'volunteer_stars_config',
      'team_stars_config',
      'wechat_message_config'
  ];


    protected $casts = [
        'module_settings' => 'array',
        'quality' => 'array',
        'score_settings' => 'array',
        'volunteer_stars_config' => 'array',
        'team_stars_config' => 'array',
        'wechat_message_config' => 'array'
    ];

    protected $appends = array('address', 'wechat_app_url');

//    public function setVolunteerStarsConfigAttribute($value) {
//        dd($value);
//        $this->attributes['volunteer_stars_config'] = [
//            '1' => $value['v1'],
//            '2' => $value['v2'],
//            '3' => $value['v3'],
//            '4' => $value['v4'],
//            '5' => $value['v5'],
//        ];
//    }
//
//    public function getVolunteerStarsConfigAttribute() {
//        if (!isset($this->attributes['volunteer_stars_config'])) {
//            return null;
//        }
//
//        return $this->attributes['volunteer_stars_config'];
//    }

    public function getQualityAttribute() {
        if (isset($this->attributes['quality'])) {
            try {
                $this->attributes['quality'] = json_decode($this->attributes['quality']);
            }catch (\Exception $e) {

            }

            if (is_array($this->attributes['quality'])) {
                return join(',', $this->attributes['quality']);
            }

            return $this->attributes['quality'];
        }

        return null;
    }

    public function setQualityAttribute($value) {
        if (!empty($value)) {
            $value = explode(',', $value);
            $value = json_encode($value);
        }

        $this->attributes['quality'] = $value;
    }

    public function setAddressAttribute($value) {
        $addressId = $value['id'];
        $this->attributes['contact_province_id'] = intval(substr($addressId, 0, 2).'0000');
        $this->attributes['contact_province_name'] = $value['province'];
        $this->attributes['contact_city_id'] = intval(substr($addressId, 0, 4).'00');
        $this->attributes['contact_city_name'] = $value['city'];
        $this->attributes['contact_county_id'] = intval(substr($addressId, 0, 6));
        $this->attributes['contact_county_name'] = $value['district'];
        $this->attributes['contact_addr'] = isset($value['address']) ? $value['address'] : '';
    }

    public function getAddressAttribute() {
        if (!isset($this->attributes['contact_county_id'])) {
            return null;
        }

        return [
            'id' => $this->attributes['contact_county_id'],
            'province' => $this->attributes['contact_province_name'],
            'city' => $this->attributes['contact_city_name'],
            'district' => $this->attributes['contact_county_name'],
            'address' => $this->attributes['contact_addr'],
        ];
    }

    public function getWechatAppUrlAttribute() {
        if (empty($this->wechat_app_id)) {
            return null;
        }
        if($this->id == 15)
        {
            return 'http://wechat'.env('BASE_HOST', '.alpha.volunteerzhiduoxing.com');
        }
        return 'http://'.$this->wechat_app_id.env('BASE_HOST', '.alpha.volunteerzhiduoxing.com');
    }


    public function getCustomConfigAttribute() {
        if (isset($this->attributes['custom_config'])) {
            try {
                $this->attributes['custom_config'] = json_decode($this->attributes['custom_config']);
            }catch (\Exception $e) {

            }

            return $this->attributes['custom_config'];
        }

        return null;
    }

    public function setCustomConfigAttribute($value) {
        if (!empty($value)) {
            $value = json_encode($value);
        }

        $this->attributes['custom_config'] = $value;
    }

    public function getWechatMessageConfigAttribute() {
        if (isset($this->attributes['wechat_message_config'])) {
            try {
                $this->attributes['wechat_message_config'] = json_decode($this->attributes['wechat_message_config']);
            }catch (\Exception $e) {

            }

            return $this->attributes['wechat_message_config'];
        }

        return null;
    }

    public function setWechatMessageConfigAttribute($value) {
        if (!empty($value)) {
            $value = json_encode($value);
        }

        $this->attributes['wechat_message_config'] = $value;
    }

    public function addCustomConfigExtends($value) {

        $customConfig = (array)$this->custom_config;

        if (!$customConfig || !isset($customConfig)) {
            $customConfig = [];
            $customConfig['extends'] = [];
            $customConfig['open_real_name'] = 0;
            $customConfig['open_avatars'] = 0;
            $customConfig['open_id_number'] = 0;
            $customConfig['open_nation'] = 0;
            $customConfig['open_addr'] = 0;
        }

//        $customConfig = json_encode($customConfig);
//        dd(gettype((array)$customConfig));
        if (array_key_exists('extends', $customConfig)) {
            $extends = $customConfig['extends'];
        } else {
            $extends = [];
        }
//        dd($customConfig, $this->custom_config);
        if (!$extends || !isset($extends)) {
            $extends = [];
        } else {
            foreach ($extends as $item) {
//                dd(gettype($item), gettype($value));
                if (gettype($item) !== 'array' ) {
                    $item = (array) $item;
                }
                if ($item && $value && $item['key'] === $value['key']) {
//                    dd()
                    return false; //key已经存在
                }
            }
        }
        $extends[] = $value;
        $customConfig['extends'] = $extends;
        $this->setCustomConfigAttribute($customConfig);
        return true;
    }

    public function editCustomConfigExtends($value) {

        $customConfig = (array)$this->custom_config;

        if (!$customConfig || !isset($customConfig)) {
            return false;
        }

        if (array_key_exists('extends', $customConfig)) {
            $extends = $customConfig['extends'];
        } else {
            $extends = [];
        }
        $new = [];
        if (!$extends || !isset($extends)) {
            return false;
        } else {
            foreach ($extends as $item) {
                if (gettype($item) !== 'array' ) {
                    $item = (array) $item;
                }
                $new[] = ($item && $value && $item['key'] === $value['key']) ? $value : $item;
            }
        }
        $customConfig['extends'] = $new;
        $this->setCustomConfigAttribute($customConfig);
        return true;
    }

    public function deleteCustomConfigExtends($key) {

        $customConfig = (array)$this->custom_config;

        if (!$customConfig || !isset($customConfig)) {
            return false;
        }

        if (array_key_exists('extends', $customConfig)) {
            $extends = $customConfig['extends'];
        } else {
            $extends = [];
        }
        $new = [];
        if (!$extends || !isset($extends)) {
            return false;
        } else {
            foreach ($extends as $item) {
                if (gettype($item) !== 'array' ) {
                    $item = (array) $item;
                }
                if ($item && $key && $item['key'] === $key) {
                    continue; // 删除该key对应的配置
                }
                $new[] = $item;
            }
        }
        $customConfig['extends'] = $new;
        $this->setCustomConfigAttribute($customConfig);
        return true;
    }

    public function getCustomConfigExtends() {
        $customConfig = (array)$this->custom_config;

        if (!$customConfig || !isset($customConfig)) {
            return null;
        }
        if (array_key_exists('extends', $customConfig)) {
            $extends = $customConfig['extends'];
        } else {
            $extends = [];
        }
//        dd($customConfig, $this->custom_config);
        if (!$extends || !isset($extends)) {
            return null;
        } else {
            return $extends;
        }
    }

    public function sortCustomConfigExtends($values) {
        $customConfig = (array)$this->custom_config;

        if (!$customConfig || !isset($customConfig)) {
            return false;
        }

        if (array_key_exists('extends', $customConfig)) {
            $extends = $customConfig['extends'];
        } else {
            $extends = [];
        }

        if (count($extends) !== count($values)) {
            return false;
        }

        $customConfig['extends'] = $values;
        $this->setCustomConfigAttribute($customConfig);
        return true;
    }

    public function getOpenCustomConfigExtends() {
        $customConfig = (array)$this->custom_config;

        if (!$customConfig || !isset($customConfig)) {
            return null;
        }

        return $customConfig;
    }

    public function setOpenCustomConfigExtends($values) {
        $customConfig = (array)$this->custom_config;

        if (!$customConfig || !isset($customConfig)) {
            $customConfig = [];
        }

        foreach ($values as $key => $value) {
            $customConfig[$key] = $value;
        }

        $this->setCustomConfigAttribute($customConfig);
    }



    public function getScoreConf()
    {
        $config = $this->score_settings;

        $config['register'] = isset($config['register'])? $config['register']:10;
        $config['certification'] = isset($config['certification'])? $config['certification']:10;
        $config['reward_time'] = isset($config['reward_time'])? $config['reward_time']:10;
        $config['project_hire'] = isset($config['project_hire'])? $config['project_hire']:10;
        unset($config['project_hire']);
        return $config;
    }

}
